package com.sgcc.nfc.lock.core.storage

import android.content.Context
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

private val Context.authDataStore by preferencesDataStore(name = "auth_prefs")

@Singleton
class TokenManager @Inject constructor(
    @ApplicationContext private val context: Context
) {

    private object Keys {
        val ACCESS_TOKEN = stringPreferencesKey("access_token")
        val REFRESH_TOKEN = stringPreferencesKey("refresh_token")
        val TOKEN_TYPE = stringPreferencesKey("token_type")
        val EXPIRES_AT = longPreferencesKey("expires_at")
    }

    val accessToken: Flow<String?> = readPreference(Keys.ACCESS_TOKEN)
    val refreshToken: Flow<String?> = readPreference(Keys.REFRESH_TOKEN)
    val tokenType: Flow<String?> = readPreference(Keys.TOKEN_TYPE)
    val expiresAt: Flow<Long?> = readPreference(Keys.EXPIRES_AT)

    suspend fun saveToken(token: AuthToken) {
        context.authDataStore.edit { prefs ->
            prefs[Keys.ACCESS_TOKEN] = token.accessToken
            prefs[Keys.REFRESH_TOKEN] = token.refreshToken
            prefs[Keys.TOKEN_TYPE] = token.tokenType ?: "Bearer"
            prefs[Keys.EXPIRES_AT] = token.expiresAt ?: 0L
        }
    }

    suspend fun clear() {
        context.authDataStore.edit { prefs ->
            prefs.clear()
        }
    }

    private fun <T> readPreference(key: Preferences.Key<T>): Flow<T?> =
        context.authDataStore.data.map { prefs -> prefs[key] }
}

data class AuthToken(
    val accessToken: String,
    val refreshToken: String,
    val tokenType: String?,
    val expiresAt: Long?
)
